from django.core.paginator import Paginator
from django.utils.translation import ugettext_lazy as _
from django.template import RequestContext, loader
from django.http import HttpResponse
from django.http import HttpRequest
from mbserver.source.models import Source, Group
from mbserver.server_lib.search import Search
import time
from django.conf import settings

def get_search_params(request):
    if 'groups' in request.GET and len(request.GET['groups']) > 0:
        search_groups = request.GET.getlist('groups')
    else:
        search_groups = []
    if 'sources' in request.GET and len(request.GET['sources']) > 0:
        search_sources = request.GET.getlist('sources')
    else:
        search_sources = []

    params = {}
    params["groups"] = []
    for group in Group.objects.filter(source__isnull=False).order_by('name').distinct():
        this_group = {
            "name": group.name,
            "id": group.id,
            "sources": [],
        }
        if unicode(group.id) in search_groups:
            this_group["is_checked"] = True
        for source in group.source_set.order_by('name').all():
            this_source = {
                "name": source.name,
                "id": source.id,
            }
            if unicode(source.id) in search_sources:
                this_source["is_checked"] = True
            this_group["sources"].append(this_source)
        params["groups"].append(this_group)

    params['sources_without_groups'] = []
    # Sources that have no group
    for source in Source.objects.filter(group__isnull=True).distinct():
        this_source = {
            "name": source.name,
            "id": source.id,
        }
        if unicode(source.id) in search_sources:
            this_source["is_checked"] = True
        params['sources_without_groups'].append(this_source)

    return params


def home(request):
    params = get_search_params(request)
    t = loader.get_template('base.html')
    c = RequestContext(request, params)
    return HttpResponse(t.render(c))

def search(request):
    start_time = time.time()
    params = get_search_params(request)
    error = False

    if 'sources' in request.GET and len(request.GET['sources']) > 0:
        params['search_sources'] = request.GET.getlist('sources')
    else:
        params['error']= _('Please select one or more sources to search')
        error = True

    if 'keywords' in request.GET and len(request.GET['keywords']) > 0:
        params['search_keywords'] = request.GET['keywords']
    else:
        params['error']= _('Please type one keyword to search')
        error = True

    if 'groups' in request.GET and len(request.GET['groups']) > 0:
        params['search_groups'] = request.GET.getlist('groups')

    if 'timeout' in request.GET:
        params['search_timeout'] = int(request.GET['timeout'])
#    else:
#        params['search_timeout'] = settings.SEARCH_TIMEOUT

    if error:
        t = loader.get_template('base.html')
        c = RequestContext(request, params)
        return HttpResponse(t.render(c))

    search = Search(params['search_keywords'], timeout=settings.SEARCH_TIMEOUT, sources=params['search_sources'])
    search.do_search()
    (results, not_returned_sources) = search.get_results()
    params['source_count'] = len(params['search_sources']) - len(not_returned_sources)
    params['result_count'] = len(results)
    params['wait_time'] = time.time() - start_time
    params['not_returned_sources'] = not_returned_sources
    params['query_string'] = request.META['QUERY_STRING']
    results_per_page = 500
    this_page_id = 1
    paginator = Paginator(results, results_per_page)
    this_page = paginator.page(this_page_id)

    params['results'] = this_page.object_list
    params['this_page'] = this_page_id
    params['num_pages'] = paginator.num_pages
    params['has_next'] = this_page.has_next()
    params['has_previous'] = this_page.has_previous()
    params['next'] = this_page.next_page_number()
    params['previous'] = this_page.previous_page_number()

    t = loader.get_template('result.html')
    c = RequestContext(request, params)
    return HttpResponse(t.render(c))
